package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 20220222version版本AZ端要求完成时间
 **/
@Service
public class AZOBRequiredCompleteTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;
    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String custId = KiteWebContext.getContext().getCust().getCustId();
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
        String serviceOfferId = querySceneInstService.getExtParameterValue(sceneInstId,"serviceOfferId");
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if(null==serviceOfferId){
            serviceOfferId =kiteSceneInst.getServiceOfferId();
        }
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        String nodeCode = StringUtils.EMPTY;
        if (Objects.nonNull(extParams)&& extParams.containsKey("nodeCode")) {
            nodeCode = KiteMapUtils.getString(extParams,"nodeCode");
        }else {
            nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        }
        // 订购、核查 操作
        String productId = prodInst.getProdId();
        if (KiteStringUtils.isEmpty(attr.getDefaultValue())) {
            getObTime(nodeCode,sceneInstId,serviceOfferId,commonAttr,attr,productId);
        }
        //setCommonAttr(commonAttr);
        operateSceneCommonService.setCommonAttr(sceneInstId, attr);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, fieldName);
        String serviceOfferId = querySceneInstService.getExtParameterValue(sceneInstId,"serviceOfferId");
        //重提初始化不校验
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams)&& extParams.containsKey("nodeCode")) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if (KeyConsts.IFTRUE_T.equals(isInitPageRenderFlag)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }

        if (KiteStringUtils.isEmpty(value)){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }

        //String allCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        //String azCompleteTimePattern = "yyyy-MM-dd";
        String completeTimePattern = LocalAttrUtils.FormatByValue(value);

        Date complateDate = null;
        Date initDate = null;
        try{
            complateDate = DateUtils.parseStrToDate(value, completeTimePattern);
            if(KiteStringUtils.isNotEmpty(attr.getDefaultValue())){
                initDate = DateUtils.parseStrToDate(attr.getDefaultValue(), completeTimePattern);
            }
        }catch (Exception e){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
        }
        if(Objects.nonNull(initDate)){
            if (null != complateDate && DateUtil.compare(initDate,complateDate) >1){
                BssException.throwOut(KeyConsts.LOG_MODULE, "", "要求完成时间不能早于初始时间");
            }
        }
        if (null != complateDate && DateUtil.compare(getCurrentDate(),complateDate) >1){
            BssException.throwOut(KeyConsts.LOG_MODULE, "", "要求完成时间不能早于当前时间");
        }
        //全程要求完成时间
        Date allCompleteDate = null;
        String allCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "ORD10012");
        if(KiteStringUtils.isNotEmpty(allCompleteTimeStr)){
            try{
                allCompleteDate = DateUtils.parseStrToDate(allCompleteTimeStr, completeTimePattern.substring(0,allCompleteTimeStr.length()));
            }catch(Exception e){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }

            //A、Z端要求完成时间 不能晚于全程要求完成时间
            if (null != complateDate && DateUtil.compare(complateDate,allCompleteDate) >1){
                BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
            }
        }



        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public Date getCurrentDate(){
        Date toDay =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String toDayStr = sdf.format(toDay);
        Date newDate = null;
        try {
            newDate = sdf.parse(toDayStr);

        }catch (Exception e){
            return newDate;
        }
        return newDate;
    }
    private void getObTime(String nodeCode,String sceneInstId,String serviceOfferId,CommonAttrVO commonAttr,KiteAttr attr,String productId){
        String value =attr.getValue();
        if(KiteStringUtils.isEmpty(attr.getDefaultValue())) {
            //接口获取工作日偏移量
            String BIZ_TYPE = querySceneInstService.getExtParameterValue(sceneInstId,"serviceOfferId");
            String nowFinishTime = null;
            if (KiteStringUtils.equalsAny(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK,serviceOfferId,BIZ_TYPE)) {
                 nowFinishTime = LocalAttrUtils.getInstance().AZOffsetDayOB(productId, null, null, LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK);
            }else {
                nowFinishTime = LocalAttrUtils.getInstance().AZOffsetDayOB(productId, null, null, null);
            }
            value = LocalAttrUtils.compareDate(commonAttr, nowFinishTime);
            attr.setValue(value);
            attr.setDefaultValue(value);
            attr.setValueDesc(value);
            commonAttr.setValue(value);
            commonAttr.setValueDesc(value);
            commonAttr.setDefaultValue(value);
        }
        value = attr.getValue();
        // 订单补录情况，来单属性为空时，不设置默认值，否则会有展示属性值与甩单填写不一致情况
        if(KiteStringUtils.isEmpty(value) &&!KiteStringUtils.isEmpty(attr.getDefaultValue())&& !KiteStringUtils.isEqual(nodeCode, "OrderAddRecord")){
            attr.setValue(attr.getDefaultValue());
            attr.setValueDesc(attr.getDefaultValue());
        }
    }
}
